package com.andy.config;

import com.andy.pojo.Configuration;
import com.andy.pojo.MappedStatement;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XmlMapperBuilder {
    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * 解析单个sqlMapper.xml
     * @param sqlMapResource
     * @throws DocumentException
     */
    public void parse(InputStream sqlMapResource) throws DocumentException, ClassNotFoundException {
        Document document = new SAXReader().read(sqlMapResource);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        List<Element> sqlElementList = rootElement.selectNodes("//select|//insert|//update|//delete");
        for (Element sqlElement : sqlElementList) {
            //拿到Sql内容
            String sqlType = sqlElement.getName();//标签类型
            String id = sqlElement.attributeValue("id");
            Class<?> paramterType = getClassType(sqlElement.attributeValue("paramterType"));
            Class<?> resultType = getClassType(sqlElement.attributeValue("resultType"));
            String sql = sqlElement.getTextTrim();
            //封装到对象中
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setSqlType(sqlType);
            mappedStatement.setSql(sql);
            mappedStatement.setParamType(paramterType);
            mappedStatement.setResulType(resultType);

            //拼接Sql的key
            String key = namespace+"."+id;

            //放入configuration
            configuration.putMappedStatement(key,mappedStatement);
        }
    }

    /**
     * 根据类路径拿到类
     * @param classTypeStr
     * @return
     * @throws ClassNotFoundException
     */
    private Class<?> getClassType(String classTypeStr) throws ClassNotFoundException {
        if(StringUtils.isBlank(classTypeStr)) return null;

        return Class.forName(classTypeStr);
    }
}
